import {Injectable, Inject} from "@angular/core";
import {DataCacheStrategy} from "./dataCacheStrategy";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {HttpResponse} from "@angular/common/http";
import {HttpErrorResponse} from "@angular/common/http";
import {ReadableMessage} from "./domain";
/**
 * Created by Administrator on 2017/4/28.
 */
@Injectable()
export class HttpHelper{
    contentHeaderEnum={
        formHeader:"application/x-www-form-urlencoded",
        jsonHeader:"application/json",
        textHeader:"text/plain"
    };

    constructor(private httpClient:HttpClient,
                private cacheStrategy:DataCacheStrategy,
                @Inject("apiUrl")public apiUrl:string){
    }
    imgUrl:string = this.apiUrl+"/images/";
    pageSize:number = 20;
    //apiUrl:String;
    private _authorization:string;
    set authorization(auth:string){
        this._authorization=auth;
    }
    get authorization():string{
        if(!this._authorization) this._authorization=this.cacheStrategy.retrieve(DataCacheStrategy.AUTHORIZATION);
        return this._authorization;
    };
    /**
    * 为http请求生成请求参数的工具函数
    * @param contentType http请求提供的内容类型
    * @param accept http请求接受的内容类型
    * @returns {{headers: Headers}}
    */
    getHeaders(pars,contentType: string = "application/json",accept?:string): any {
        let hs = new HttpHeaders();
        if(contentType) hs.append("Content-Type", contentType);
        hs.append("Authorization", this.authorization);
        if(accept)  hs.append("Accept",accept);
        return {headers: hs,observe:"response",params:pars};
    }

    getJson<T>(url:string,pars):Promise<T>{
        return this.httpClient.get<HttpResponse<T>>(this.apiUrl+url,this.getHeaders(pars,null,"application/json"))
            .toPromise()
            .then((rst:any)=>rst.body)
            .catch(resp=>this.handleError(resp));
    }

    getBoolean(url:string,pars):Promise<boolean>{
        return this.httpClient.get(this.apiUrl+url,this.getHeaders(pars,null,"text/plain"))
            .toPromise()
            .then((res:any)=>/true/.test(res.body))
            .catch(err=>this.handleError(err));
    }
    getText(url:string,pars):Promise<string>{
        return this.httpClient.get<HttpResponse<string>>(this.apiUrl+url,this.getHeaders(pars,null,"text/plain"))
            .toPromise()
            .then((res:any)=>res.body)
            .catch(err=>this.handleError(err));
    }

    postToJson<T>(url:string,pars,entity:any,contentType:string="application/json"):Promise<T>{
        return this.httpClient.post(this.apiUrl+url,entity,this.getHeaders(pars,contentType,"application/json"))
            .toPromise()
            .then((res:any)=>res.body)
            .catch(err=>this.handleError(err));
    }
    postToBoolean(url:string,pars,entity:any,contentType:string="application/json"):Promise<boolean>{
        return this.httpClient.post(this.apiUrl+url,entity,this.getHeaders(pars,contentType,"text/plain"))
            .toPromise()
            .then((res:any)=>/true/.test(res.body))
            .catch(err=>this.handleError(err));
    }
    postToText(url:string,pars,entity:any,contentType:string="application/json"):Promise<string>{
        return this.httpClient.post(this.apiUrl+url,entity,this.getHeaders(pars,contentType,"text/plain"))
            .toPromise()
            .then((res:any)=>res.body)
            .catch(err=>this.handleError(err));
    }
    putToJson<T>(url:string,pars,entity:any,contentType:string="application/json"){
        return this.httpClient.put(this.apiUrl+url,entity,this.getHeaders(pars,contentType))
            .toPromise()
            .then((res:any)=>res.body)
            .catch(err=>this.handleError(err));
    }
    putToBoolean(url:string,pars,entity:any,contentType:string="application/json"):Promise<boolean>{
        return this.httpClient.put(this.apiUrl+url,entity,this.getHeaders(pars,contentType,"text/plain"))
            .toPromise()
            .then((res:any)=>/true/.test(res.body))
            .catch(err=>this.handleError(err));
    }
    putToText(url:string,pars,entity:any,contentType:string="application/json"):Promise<string>{
        return this.httpClient.put(this.apiUrl+url,entity,this.getHeaders(pars,contentType,"text/plain"))
            .toPromise()
            .then((res:any)=>res.body)
            .catch(err=>this.handleError(err));
    }
    remove(url:string,pars):Promise<boolean>{
        return this.httpClient.delete(this.apiUrl+url,this.getHeaders(pars))
            .toPromise()
            .then((res:any)=>/true/.test(res.body))
            .catch(err=>this.handleError(err));
    }
  /**
   * 解析http错误回应的工具函数
   * @param errRes http请求返回的错误回应
   * @returns ReadableMessage
   */
  private handleError(errRes: HttpErrorResponse):Promise<any> {
      let msg:ReadableMessage=null;
      switch(errRes.status){
          case 200:
              msg= new ReadableMessage("网络错误或服务器无法响应",true);
              break;
          case 488:
          case 444:
              msg= errRes.error;
              break;
          case 404:
              msg= new ReadableMessage("请求的页面不存在",false);
              break;
          case 500:
              msg= new ReadableMessage(`服务器未响应,请稍后再试!`,true,errRes.message);
              break;
          default:
              msg=errRes.error;
      }
      return Promise.reject<ReadableMessage>(msg);
  };

}
